package com.hongxun.design.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.CreateProjectAttributeAdapter;
import com.hongxun.design.adapters.CreateProjectAttributeCodeSetSysAdapter;
import com.hongxun.design.adapters.CreateRADIOAdapter;
import com.hongxun.design.adapters.MultiSelectAdapter;
import com.hongxun.design.bean.CreateDistanceBean;
import com.hongxun.design.bean.UnitBean;
import com.hongxun.design.bean.UnitsBean;
import com.hongxun.design.bean.UserBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.interfaces.UpdateMap;
import com.hongxun.design.jungong.dialog.ProjectParticipantsDialog;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.MyLocationListenner;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.MBaiduMap;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringCodeTableUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.maputil.GeoCodeUtil;

import java.util.List;

/**
 * Created by zerdoor_pc on 2016/4/29.
 * 创建项目中地图、多选、单选详情页
 */
public class CreateProjectAttributeActivity extends BaseActivity implements HeadSecond,
        OnGetGeoCoderResultListener, UpdateMap {
    String title = "无";//标题
    public static String TYPENUM = "";//标题
    int style = View.VISIBLE;//是否显示保存按钮
    String type = Constant.ACTIVITYNO;//界面显示类型
    ListView attribute_list;//适配类型
    List<CreateDistanceBean> data;//适配数据
    CreateProjectAttributeAdapter adapter;//适配器
    //单选与多选
    String DataCode = "";//多选字段数据标识
    MultiSelectAdapter multiAdapter;//多选适配器
    CreateRADIOAdapter radioAdapter;//单选选适配器
    private static Handler unitHandler;
    private static Handler personnelHandler;
    List<UserBean> unitUsersData;//人员数据
    List<UnitBean> unitsData;//单位数据
    // 定位相关
    public MyLocationListenner myListener;
    private String finishAdress = "";
    BaiduMap mBaiduMap;
    MapView mMapView;
    MBaiduMap baidumapstyle;
    public static LatLng currentPt;//经纬
    double altitude;//海拔
    TextView words;//显示地名
    GeoCodeUtil geoCodeUtil = null;
    public String Code, id, stage_id = "";
    public String code;//判断典设进入口
    //new
    Button btnadd;//添加项目参与人

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_createprojectattribute);
        type = getIntent().getExtras().getString(MString.TYPE);
        TYPENUM = getIntent().getExtras().getString(MString.TYPENUM);
        findBar();
        findView();
        initialization();
    }

    @Override
    protected void onStart() {
        MyApp.activity = this;
        super.onStart();
    }

    /**
     * 得到初始标题与相关信息*
     */
    @SuppressLint("NewApi")
    private void getName() {
        switch (type) {
            case Constant.ACTIVITYMAP:
                //地图
                title = "地址定位";
                break;
            case Constant.ACTIVITYCODESET:
                //典设版本
                title = "典设版本";
                style = View.GONE;
                code = getIntent().getExtras().getString(MString.CODE, MString.click_in);
                break;
            case Constant.ACTIVITYMULTISELECT:
                //多选
                title = getIntent().getExtras().getString(MString.TITLE);
                DataCode = getIntent().getExtras().getString(MString.SENDCODE);
                id = getIntent().getExtras().getString(MString.userid, "");
                stage_id = getIntent().getExtras().getString(MString.stage_id, "");
                break;
            case Constant.ACTIVITYRADIO:
                //单选
                title = getIntent().getExtras().getString(MString.TITLE);
                DataCode = getIntent().getExtras().getString(MString.SENDCODE);
                Code = getIntent().getExtras().getString(MString.CODE, "");
                style = View.INVISIBLE;
                break;
        }
    }

    @Override
    public void findBar() {
        getName();
        btnadd = (Button) findViewById(R.id.attribute_btn_add);
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.headsecond_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.Save, style, R.color.bar_right, ListenerSet.back,
                title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setReturnData();
            }
        });
        //项目参与人+会员中心人
        if (DataCode.equals("12") && MyApp.userInfo.getOrg_type().equals("10")) {
            btnadd.setVisibility(View.VISIBLE);
            btnadd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ProjectParticipantsDialog dialog = new ProjectParticipantsDialog();
                    dialog.setHandler(personnelHandler);
                    dialog.setUserid(id);
                    dialog.show(getSupportFragmentManager(), "cpa");
                }
            });
        } else {
            btnadd.setVisibility(View.GONE);
        }
    }

    private void setReturnData() {
        if (type.equals(Constant.ACTIVITYMAP)) {
            if (currentPt.longitude < 0 || currentPt.latitude < 0
                    || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
                ToastShow.showShort(mActivity, "定位失败！");
                return;
            }
            double[] d = null;
            if (currentPt != null) {
                d = new double[]{currentPt.longitude, currentPt.latitude, altitude};
            }
            CreateProjectActivity.setValue(Constant.ACTIVITYMAP, finishAdress, d);
            finish();
        } else if (type.equals(Constant.ACTIVITYMULTISELECT)) {
            List<UserBean> back = (List<UserBean>) multiAdapter.getChecked();
            if (back.size() > 0) {
                CreateProjectActivity.setValue(Constant.ACTIVITYMULTISELECT, multiAdapter.getChecked(), TYPENUM);
                finish();
            } else {
                ToastShow.showShort(mActivity, "选择不能为空！");
            }
        }
    }

    @Override
    protected void findView() {
        LinearLayout attribute_bg;
        switch (type) {
            case Constant.ACTIVITYMAP:
                //地图
                findView_Map();
                break;
            case Constant.ACTIVITYCODESET:
                //典设
                attribute_bg = (LinearLayout) findViewById(R.id.attribute_bg);
                attribute_bg.setBackgroundResource(R.color.white);
                findView_Soil();
                break;
            case Constant.ACTIVITYMULTISELECT:
                //多选
                attribute_bg = (LinearLayout) findViewById(R.id.attribute_bg);
                attribute_bg.setBackgroundResource(R.color.white);
                findView_Soil();
                break;
            case Constant.ACTIVITYRADIO:
                //单选
                attribute_bg = (LinearLayout) findViewById(R.id.attribute_bg);
                attribute_bg.setBackgroundResource(R.color.white);
                findView_Soil();
                break;
        }
        super.findView();
    }

    /**
     * 地图控件
     */
    private void findView_Map() {
        LinearLayout attribute_mapui = (LinearLayout) findViewById(R.id.attribute_mapui);
        attribute_mapui.setVisibility(View.VISIBLE);
        words = (TextView) findViewById(R.id.words);
        baidumapstyle = (MBaiduMap) findViewById(R.id.baidumapstyle);
        mMapView = baidumapstyle.getMapView();
        mBaiduMap = baidumapstyle.getBaiduMap();
        baidumapstyle.setPositionClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //重新定位
                inItLocation();
            }
        });
    }

    /**
     * 卫星图
     **/
    boolean isstylesatellite = false;

    public void ChangeSatellite(View v) {
        if (isstylesatellite) {
            isstylesatellite = false;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.style_satellite));
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        } else {
            isstylesatellite = true;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.style_map));
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
        }
    }

    /**
     * 非地图的控件*
     */
    private void findView_Soil() {
        attribute_list = (ListView) findViewById(R.id.attribute_list);
        attribute_list.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initialization() {
        switch (type) {
            case Constant.ACTIVITYMAP:
                //地图
                initialization_Map();
                break;
            case Constant.ACTIVITYCODESET:
                //典设版本
                initialization_CodeSet();
                break;
            case Constant.ACTIVITYMULTISELECT:
                //多选框
                initialization_MULTI();
                break;
            case Constant.ACTIVITYRADIO:
                //单选框
                initialization_RADIO();
                break;
        }
        super.initialization();
    }

    /**
     * 地图初始化
     */
    private void initialization_Map() {

        geoCodeUtil = GeoCodeUtil.getInstence(this);
        mMapView.getMapLevel();

        if (MyApp.bdLocation == null) {
            MyLog.L(MString.SUCCESSED + "MyApp.bdLocation=null");
            inItLocation();
        } else {
            MyLog.L(MString.SUCCESSED + " MyApp.bdLocation!=null " + MyApp.bdLocation.getLatitude() + "  " + MyApp.bdLocation.getLongitude());
            currentPt = new LatLng(MyApp.bdLocation.getLatitude(),
                    MyApp.bdLocation.getLongitude());
            altitude = MyApp.bdLocation.getAltitude();
            updateMapState();
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(currentPt).zoom(MyApp.zoom).build()));
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
        }
        initListener();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    ACCESS_COARSE_LOCATION);
        }
        if (!MyApp.NetWorkConnect) {
            ToastShow.showShort(this, "网络异常，请检查网络！");
        }

        LocationManager alm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            ToastShow.showShort(this, "GPS未开启,请打开GPS！");
        }

    }

    private int READ_SYNC_SETTINGS = 100;
    private int ACCESS_COARSE_LOCATION = 101;
    private int ACCESS_FINE_LOCATION = 102;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_SYNC_SETTINGS) {
            ToastShow.showShort(this, "百度地图权限未打开，请到设置里面开启！");
        } else if (requestCode == ACCESS_COARSE_LOCATION) {
            ToastShow.showShort(this, "网络定位权限未打开，请到设置里面开启！");
        } else if (requestCode == ACCESS_FINE_LOCATION) {
            ToastShow.showShort(this, "GPS权限未开启，请到设置里面开启！");
        }
    }

    /**
     * 典设初始化
     */
    private void initialization_CodeSet() {
        if (attribute_list == null) return;
        List<SystemTypeBean> beans = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.codesetType);
        CreateProjectAttributeCodeSetSysAdapter codeSetAdapter = new CreateProjectAttributeCodeSetSysAdapter(beans, this);
        attribute_list.setAdapter(codeSetAdapter);
    }

    /**
     * 多选框初始化
     */
    private void initialization_MULTI() {
        inItPersonnelHander();
        if (MyApp.isOnLine) {
            MyApp.HTTP.getPersonnelList(personnelHandler, HttpStringUtil.SUCCESSED, DataCode, stage_id);
        } else {
            personnelHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED,
                    ShardPreferencesTool.getshare(this, MString.UserByTypeList + DataCode, "")));
        }
    }

    private void initialization_MULTI_adapter() {
        if (unitUsersData == null) return;
        multiAdapter = new MultiSelectAdapter(unitUsersData, this, id);
        attribute_list.setAdapter(multiAdapter);
    }

    /**
     * 单选框初始化
     */
    private void initialization_RADIO() {
        inItUnitHander();
        MyApp.HTTP.getListOfUnits(unitHandler, HttpStringUtil.SUCCESSED, DataCode);
    }

    private void initialization_RADIO_Adapter() {
        if (unitsData == null) return;
        radioAdapter = new CreateRADIOAdapter(unitsData, this);
        attribute_list.setAdapter(radioAdapter);
    }

    private void inItUnitHander() {
        unitHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            List<UnitsBean> units = FastJsonUtil.JsonUnitData((String) msg.obj, DataCode);
                            if (units == null || units.size() == 0) return;
                            unitsData = units.get(0).getUnits();
                            unitHandler.sendEmptyMessage(ADDADAPTER);
                        } else {
                            ToastShow.showShort(mActivity, s);
                        }
                        break;
                    case ADDADAPTER:
                        initialization_RADIO_Adapter();
                        break;
                    case HttpStringUtil.ERROR:

                        break;

                }
            }
        };
    }

    private final int ADDADAPTER = 1;

    private void inItPersonnelHander() {
        personnelHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            unitUsersData = FastJsonUtil.JsonPersonnelData((String) msg.obj, DataCode).get(0).getUnitsUser();
                            personnelHandler.sendEmptyMessage(ADDADAPTER);
                        }
                        break;
                    case ADDADAPTER:
                        initialization_MULTI_adapter();
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                    case 2:
                        boolean isadd = false;
                        UserBean bean = (UserBean) msg.obj;
                        for (UserBean userBean : unitUsersData) {
                            if (userBean.getId().equals(bean.getId())) {
                                isadd = true;
                                break;
                            }
                        }
                        if (!isadd) {
                            unitUsersData.add(bean);
                            id = id + "," + bean.getId();
                            multiAdapter = new MultiSelectAdapter(unitUsersData, getApplicationContext(), id);
                            attribute_list.setAdapter(multiAdapter);
                            multiAdapter.notifyDataSetChanged();
                        }
                        break;
                }
            }
        };
    }

    /************************地图相关方法***********************************************************/

    /**
     * 以下为地图相关方法*
     */
    private void inItLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        myListener = MyLocationListenner.getint(mMapView, this);
        myListener.setIsFirstLoc(true);

    }

    //点击监听
    private void initListener() {

        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {

            @Override
            public void onTouch(MotionEvent event) {

            }
        });

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            public void onMapClick(LatLng point) {
            }

            public boolean onMapPoiClick(MapPoi poi) {
                return false;
            }
        });
        mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            public void onMapLongClick(LatLng point) {
            }
        });
        mBaiduMap.setOnMapDoubleClickListener(new BaiduMap.OnMapDoubleClickListener() {
            public void onMapDoubleClick(LatLng point) {
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            LatLng startLng, finishLng;

            public void onMapStatusChangeStart(MapStatus status) {
                startLng = status.target;
            }

            public void onMapStatusChangeFinish(MapStatus status) {
                finishLng = status.target;
                if (startLng.latitude != finishLng.latitude
                        || startLng.longitude != finishLng.longitude) {

                    MyLog.L(MString.SUCCESSED + "s=" + JSON.toJSONString(mBaiduMap.getMapStatus().bound.getCenter()));
                    currentPt = mBaiduMap.getMapStatus().bound.getCenter();
                    updateMapState(currentPt);

                }
            }

            public void onMapStatusChange(MapStatus status) {

            }
        });

    }

    /**
     * 更新地图状态显示面板
     */
    public void updateMapState() {
        if (words == null) {
            return;
        }
        if (geoCodeUtil != null && currentPt != null) {
            geoCodeUtil.LatLngToAdress(currentPt);
        }

    }

    public void updateMapState(LatLng currentPt) {
        this.currentPt = currentPt;
        if (MyApp.bdLocation != null) altitude = MyApp.bdLocation.getAltitude();
        if (MyApp.NetWorkConnect) {
            if (geoCodeUtil != null && currentPt != null) {
                geoCodeUtil.LatLngToAdress(currentPt);
            }
        } else if (currentPt != null) {
            setMarka(currentPt);
            if (currentPt.longitude < 0 || currentPt.latitude < 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
                words.setText("");
                finishAdress = "";
            } else {
                String strInfo = String.format("纬度：%f 经度：%f",
                        currentPt.latitude, currentPt.longitude);
                words.setText(strInfo);
                finishAdress = strInfo;
            }
        }

    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
        if (result == null || result.getAddress().length() == 0 || result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastShow.showShort(this, "抱歉，未能找到结果");
            if (currentPt.longitude < 0 || currentPt.latitude < 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
                words.setText("");
                finishAdress = "";
            } else {
                setMarka(currentPt);
                String strInfo = String.format("纬度：%f 经度：%f",
                        currentPt.latitude, currentPt.longitude);
                words.setText(strInfo);
                finishAdress = strInfo;
            }

            return;
        }


        setMarka(result.getLocation());
//        String strInfo = String.format("纬度：%f 经度：%f",
//                result.getLocation().latitude, result.getLocation().longitude);
        // ToastShow.showShort(this, strInfo);
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        try {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR || result.getAddress().length() == 0) {
                ToastShow.showShort(this, "抱歉，未能找到结果");
                if (currentPt.latitude <= 0 || currentPt.longitude <= 0 || currentPt.longitude == 4.9E-324 || currentPt.latitude == 4.9E-324) {
                    words.setText("");
                    finishAdress = "";
                    return;
                }
                setMarka(currentPt);
                String strInfo = String.format("纬度：%f 经度：%f",
                        currentPt.latitude, currentPt.longitude);
                words.setText(strInfo);
                finishAdress = strInfo;
                return;
            }
        } catch (Exception e) {
            return;
        }

        setMarka(result.getLocation());
        words.setText(result.getAddress());
        finishAdress = result.getAddress();
        //ToastShow.showShort(this, result.getAddress());
    }

    private void setMarka(LatLng point) {
        baidumapstyle.setMarka(point, "");
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
    }

    @Override
    protected void onPause() {
        if (mMapView != null) {
            mMapView.onPause();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mMapView != null) {
            mMapView.onResume();
        }
        MyApp.activity = this;
        mActivity = this;
        baseActivity = this;
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mMapView != null) {
            try {
                geoCodeUtil.onDestroy();
                // 关闭定位图层
                mBaiduMap.setMyLocationEnabled(false);
                mMapView.onDestroy();
                mMapView = null;

            } catch (Exception e) {
            }
        }
        unitHandler = null;
        personnelHandler = null;
        unitsData = null;
        unitUsersData = null;
        adapter = null;
        data = null;
        multiAdapter = null;
        radioAdapter = null;
        super.onDestroy();
    }
}
